﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EDiamondModel;
public partial class Pages_CheckoutReview : System.Web.UI.Page
{
    private bool Check()
    {
        if (Session["Madn"] == null || Session["Madn"].ToString() == "")
        {
            Response.Redirect("~/Pages/GioHang.aspx");
            return false;
        }
        return true;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!Check())
                return;
            string NguoiDungID = Session["Madn"].ToString();
            if (Request.QueryString["TT"] != null && Request.QueryString["TT"] == "1")
            {
                EDiamondEntities1 db = new EDiamondEntities1();
                var myOrder = new DatHang();
                myOrder.NgayDatHang = DateTime.Now;
                myOrder.KhachHangID = int.Parse(NguoiDungID);
                if (Session["DiaChi"] != null)
                {
                    myOrder.DiaChi = Session["DiaChi"].ToString();
                    DiaChi.Text = myOrder.DiaChi;
                }
                if (Session["ThanhPho"] != null && Session["ThanhPho"].ToString() != "-1")
                {
                    myOrder.IdThanhPho = int.Parse(Session["ThanhPho"].ToString());
                    var tp = db.ThanhPhoes.Single(xx => xx.Id == myOrder.IdThanhPho);
                    ThanhPho.Text = tp.TenThanhPho;
                    QuocGia.Text = tp.Nuoc.TenNuoc;
                }

                myOrder.IdHinhThucVanChuyen = int.Parse(Session["IdHinhThucVanChuyen"].ToString());
                // Verify total payment amount as set on CheckoutStart.aspx.

                myOrder.TriGia =int.Parse(Session["payment_amt"].ToString());
                if (Session["giavanchuyen"] != null && Session["giavanchuyen"].ToString() != "")
                    myOrder.TriGia += int.Parse(Session["giavanchuyen"].ToString());
                Total.Text = myOrder.TriGia.ToString();
                // Get DB context.
                EDiamondEntities1 _db = new EDiamondEntities1();

                // Add order to DB.
                _db.DatHangs.AddObject(myOrder);
                _db.SaveChanges();


                List<MuaSanPham> myOrderList = HttpContext.Current.Session["GioHang"] as List<MuaSanPham>;

                // Add OrderDetail information to the DB for each product purchased.
                for (int i = 0; i < myOrderList.Count; i++)
                {
                    // Create a new OrderDetail object.
                    var myOrderDetail = new DatHangCT();
                    myOrderDetail.DatHangID = myOrder.DatHangID;
                    myOrderDetail.SanPhamID = myOrderList[i].SanPhamID;
                    myOrderDetail.SoLuong = myOrderList[i].Soluong;
                    myOrderDetail.DonGia = myOrderList[i].Dongia;
                    myOrderDetail.ThanhTien = myOrderDetail.SoLuong * myOrderDetail.DonGia;
                    // Add OrderDetail to DB.
                    _db.DatHangCTs.AddObject(myOrderDetail);
                    _db.SaveChanges();
                }

                // Set OrderId.
                Session["currentOrderId"] = myOrder.DatHangID;
                // Display OrderDetails.
                OrderItemList.DataSource = myOrderList;
                OrderItemList.DataBind();
                CheckoutConfirm.Visible = false;
                lbThongBao.Text = "Đặt hàng thành công";
                Session["GioHang"] = new List<MuaSanPham>();
            }
            else
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string retMsg = "";
                string token = "";
                string PayerID = "";
                NVPCodec decoder = new NVPCodec();
                token = Session["token"].ToString();

                bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerId"] = PayerID;
                    EDiamondEntities1 db = new EDiamondEntities1();
                    var myOrder = new DatHang();
                    myOrder.NgayDatHang = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                    myOrder.KhachHangID = int.Parse(NguoiDungID);
                    if (Session["DiaChi"] != null)
                    {
                        myOrder.DiaChi = Session["DiaChi"].ToString();
                        DiaChi.Text = myOrder.DiaChi;
                    }
                    if (Session["ThanhPho"] != null && Session["ThanhPho"].ToString() != "-1")
                    {
                        myOrder.IdThanhPho = int.Parse(Session["ThanhPho"].ToString());
                        var tp = db.ThanhPhoes.Single(xx => xx.Id == myOrder.IdThanhPho);
                        ThanhPho.Text = tp.TenThanhPho;
                        QuocGia.Text = tp.Nuoc.TenNuoc;
                    }
                    myOrder.TriGia = int.Parse(Convert.ToDouble(decoder["AMT"].ToString()).ToString());
                    
                    myOrder.PayID = PayerID;
                    myOrder.IdHinhThucVanChuyen = int.Parse(Session["IdHinhThucVanChuyen"].ToString());
                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        
                        decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
                        
                        if (myOrder.TriGia != paymentAmoutFromPayPal)
                        {
                            Response.Redirect("~/Pages/CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("~/Pages/CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    // Get DB context.
                    EDiamondEntities1 _db = new EDiamondEntities1();

                    // Add order to DB.
                    _db.DatHangs.AddObject(myOrder);
                    _db.SaveChanges();


                    List<MuaSanPham> myOrderList = HttpContext.Current.Session["GioHang"] as List<MuaSanPham>;

                    // Add OrderDetail information to the DB for each product purchased.
                    for (int i = 0; i < myOrderList.Count; i++)
                    {
                        // Create a new OrderDetail object.
                        var myOrderDetail = new DatHangCT();
                        myOrderDetail.DatHangID = myOrder.DatHangID;
                        myOrderDetail.SanPhamID = myOrderList[i].SanPhamID;
                        myOrderDetail.SoLuong = myOrderList[i].Soluong;
                        myOrderDetail.DonGia = myOrderList[i].Dongia;
                        // Add OrderDetail to DB.
                        _db.DatHangCTs.AddObject(myOrderDetail);
                        _db.SaveChanges();
                    }

                    // Set OrderId.
                    Session["currentOrderId"] = myOrder.DatHangID;

                    // Display Order information.
                    Total.Text = myOrder.TriGia.ToString();


                    // Display OrderDetails.
                    OrderItemList.DataSource = myOrderList;
                    OrderItemList.DataBind();

                }
                else
                {
                    Response.Redirect("~/Pages/CheckoutError.aspx?" + retMsg);
                }
            }
        }
    }

    protected void CheckoutConfirm_Click(object sender, EventArgs e)
    {
        Session["userCheckoutCompleted"] = "true";
        NVPAPICaller payPalCaller = new NVPAPICaller();

        string retMsg = "";
        string token = "";
        string finalPaymentAmount = "";
        string PayerID = "";
        NVPCodec decoder = new NVPCodec();

        token = Session["token"].ToString();
        PayerID = Session["payerId"].ToString();
        if (Session["giavanchuyen"] != null && Session["giavanchuyen"].ToString() != "")
            finalPaymentAmount = (double.Parse(Session["payment_amt"].ToString()) + double.Parse(Session["giavanchuyen"].ToString())).ToString();
        else
            finalPaymentAmount = Session["payment_amt"].ToString();
        bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
        if (ret)
        {
            // Retrieve PayPal confirmation value.
            string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();

            EDiamondEntities1 _db = new EDiamondEntities1();
            // Get the current order id.
            int currentOrderId = -1;
            if (Session["currentOrderId"] != string.Empty)
            {
                currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
            }
            DatHang myCurrentOrder;
            if (currentOrderId >= 0)
            {
                // Get the order based on order id.
                myCurrentOrder = _db.DatHangs.Single(o => o.DatHangID == currentOrderId);
                // Update the order to reflect payment has been completed.
                myCurrentOrder.PayID = PaymentConfirmation;
                // Save to DB.
                _db.SaveChanges();
            }
            Session["giavanchuyen"] = null;
            Session["GioHang"] = new List<MuaSanPham>();
            // Clear order id.
            Session["currentOrderId"] = string.Empty;
            lbThongBao.Text = "Đặt hàng thành công";
            CheckoutConfirm.Visible = false;
        }
        else
        {
            Session["giavanchuyen"] = null;
            Session["GioHang"] = new List<MuaSanPham>();
            // Clear order id.
            Session["currentOrderId"] = string.Empty;

            Response.Redirect("~/Pages/GioHang.aspx?Loi=" + retMsg);

        }
    }

}